package com.linx.rxlife

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent

abstract class Life(
    protected val owner: LifecycleOwner,
    private val atLeastState: Lifecycle.State = Lifecycle.State.STARTED
) : LifecycleObserver {

    private var isActive = false

    @Suppress("unused")
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onEvent() {
        if (owner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
            onInactive()
            owner.lifecycle.removeObserver(this)
        } else {
            activeStateChange(shouldBeActive())
        }
    }

    abstract fun onActive()

    abstract fun onInactive()

    protected fun shouldBeActive(): Boolean {
        return owner.lifecycle.currentState.isAtLeast(atLeastState)
    }

    protected fun activeStateChange(newActive: Boolean) {
        if (newActive != isActive) {
            isActive = newActive
            if (newActive) {
                onActive()
            } else {
                onInactive()
            }
        }
    }

}